<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row v-show="!switchFlag" class="query-form" style="padding-top: 10px">
                <Col span="8">
                    <FormItem label="协议名称：">
                        <Input type="text" v-model="form1.agreementName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="企业名称：">
                        <Input type="text" v-model="form1.contractorName"/>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form" style="padding-top: 10px">
                <Col span="8">
                    <FormItem label="协议名称：">
                        <Input type="text" v-model="form1.agreementName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="企业名称：">
                        <Input type="text" v-model="form1.contractorName"/>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="所属单位：">
                        <cascaderDom ref="childOrg" @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                                     :rootOrgId="companyId"
                                     :orgTree="true"></cascaderDom>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" :loading="loading" size="small" class="table" no-data-text="没有查询到相关数据!"
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
                      style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>

        <Modal :transfer=false v-model="model1" :width=700 :title="add?'相关方安全协议新增':'相关方安全协议修改'"
               @on-cancel="onCancel">
            <div>
                <Form style="margin-left: 10px" ref='InputData' :model="InputData" :rules="ruleCustom"
                      label-position="top">
                    <Row style="line-height: 42px;">
                        <Col span='11'>
                            <FormItem label='协议编号：' prop="agreementNum">
                                <Input v-model="InputData.agreementNum"/>
                            </FormItem>
                        </Col>
                        <Col span='11' offset="1">
                            <FormItem label='协议名称：' prop="agreementName">
                                <Input v-model="InputData.agreementName"/>
                            </FormItem>
                        </Col>
                        <Col span='11'>
                            <FormItem label='企业名称：' prop="contractorName">
                                <Input v-model="InputData.contractorName" readonly @on-focus="selectContractor"/>
                                <!--<Button slot="append" @click="selectContractor" icon="ios-search"></Button>-->
                                <!--</Input>-->
                            </FormItem>
                        </Col>
                        <Col span='11' offset="1">
                            <FormItem label='协议有效期：' prop="validDate">
                                <Date-picker type="daterange" style="width: 100%" v-model="validDate"/>
                            </FormItem>
                        </Col>
                        <Col span='23'>
                            <FormItem label='备注：' prop="notes">
                                <Input v-model="InputData.notes" type="textarea" :autosize="{minRows:2,maxRows:5}"/>
                            </FormItem>
                        </Col>
                        <Col span="23">
                            <FormItem label="协议附件：">
                                <div>
                                    <Upload ref="upload"
                                            :before-upload="beforeUpload"
                                            :show-upload-list="true"
                                            :max-size="10240"
                                            multiple
                                            type="drag"
                                            :action="fileUrl">
                                        <div style="padding: 10px">
                                            <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                            <p>点击将文件拖拽到这里上传</p>
                                            <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                        </div>
                                    </Upload>
                                </div>
                                <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                    <a @click="downloadFile(InputData.agreementId,item)">{{ item.fileName }}</a>
                                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                            style="margin-left: 5px;margin-bottom: 3px"/>

                                </div>
                            </FormItem>
                        </Col>
                    </Row>
                    <!-- <Row type="flex" justify="space-around" class="code-row-bg">
                         <Col span="23">
                             <FormItem>
                                 <Button  class='ivu-btn-save'  :loading="buttonLoading" @click="submit('InputData')">确定</Button>
                                 <Button class='ivu-btn-cancel' @click="onCancel">取消</Button>
                             </FormItem>
                         </Col>
                     </Row>-->
                </Form>
            </div>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="submit('InputData')">确定</Button>
                <Button class='ivu-btn-cancel' @click="onCancel">取消</Button>
            </div>
        </Modal>

        <Modal v-model="model2" footer-hide :width=800 title="相关方台账">
            <Form ref="pageModel2" :model="pageModel2" :label-width="120">
                <Row class="query-form">
                    <Col span="8">
                        <FormItem label="企业名称：">
                            <Input type="text" v-model="pageModel2.contractorName"/>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="selectContractor()">查询</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span="24">
                        <Table height="300" :loading="loading" size="small" class="table" no-data-text="没有查询到相关数据!"
                               @on-row-dblclick="danxuan"
                               highlight-row stripe border :columns="columns2" width="100%" :data="contractor">
                        </Table>
                    </Col>
                </Row>
                <Row style="margin-right:10px;">
                    <Col span="24">
                        <Page :total="pageModel2.total" :page-size="pageModel2.pageSize" @on-change="pageChange1"
                              style="float: right" @on-page-size-change="pageSizeChange1"
                              :page-size-opts="pageSizeArray"
                              show-total show-sizer show-elevator/>
                    </Col>
                </Row>
            </Form>
            <!--<div slot="footer">
                &lt;!&ndash;<Button type="text" @click="model2=false,buttonLoading=false">取消</Button>&ndash;&gt;
                &lt;!&ndash;<Button    :disabled="buttonLoading" @click="baocun">确定</Button>&ndash;&gt;
            </div>-->
        </Modal>

        <Modal :transfer=false v-model="model3" :width=700 title="相关方安全协议"
               @on-cancel="onCancel">
            <Form style="margin-left: 10px" :model="InputData" label-position="top">
                <Row style="line-height: 42px;">
                    <Col span='11'>
                        <span>协议编号：{{InputData.agreementNum}}</span>
                    </Col>
                    <Col span='11' offset="1">
                        <span>协议名称：{{InputData.agreementName}}</span>
                    </Col>
                </Row>
                <Row class="detail-background-clor" style="line-height: 42px;">
                    <Col span='11'>
                        <span>企业名称：{{InputData.contractorName}}</span>
                    </Col>
                    <Col span='11' offset="1">
                        <span>协议有效期：{{validDate1}}</span>
                    </Col>
                </Row>
                <Row style="line-height: 42px;">
                    <Col span='23'>
                        <span>备注：{{InputData.notes}}</span>
                    </Col>
                </Row>
                <Row class="detail-background-clor" style="line-height: 42px;">
                    <Col span="23">
                        <FormItem label="协议附件：">
                            <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                <a @click="downloadFile(InputData.agreementId,item)">{{ item.fileName }}</a>
                            </div>
                        </FormItem>
                    </Col>
                </Row>
                <!-- <Row type="flex" justify="space-around" class="code-row-bg">
                     <Col span="23">
                         <FormItem>
                             <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
                         </FormItem>
                     </Col>
                 </Row>-->
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>
    import {Api} from '../../../api/index.js'
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import cascaderDom from '../../../components/cascader-dom.vue';

    export default {
        components: {cascaderDom},
        name: "interestedPartiesSecurityProtocol",
        data() {
            return {
                tableHeight: '',
                switchFlag: false,
                loading: false,
                form1: {
                    agreementName: '',
                    contractorName: '',
                    orgId: '',
                    orgName: ''
                },
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable: [],
                ruleCustom: {
                    agreementName: [{
                        message: '  ',
                        required: true,
                        trigger: 'blue'
                    }],
                    agreementNum: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    contractorName: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    validDate: [{
                        validator: (rule, value, callback) => {
                            if (this.validDate == null || this.validDate[0] == null) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    notes: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                },
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    }, {
                        width: 200,
                        minWidth: 150,
                        title: '协议编号',
                        align: 'center',
                        key: 'agreementNum',
                    },
                    {
                        width: 150,
                        title: '协议名称',
                        align: 'center',
                        key: 'agreementName',
                    },
                    {
                        width: 200,
                        minWidth: 150,
                        title: '企业名称',
                        align: 'center',
                        key: 'contractorName',
                    },
                    {
                        width: 200,
                        minWidth: 150,
                        title: '所属单位',
                        align: 'center',
                        key: 'companyName',
                    },
                    {
                        minWidth: 150,
                        title: '协议有效期',
                        align: 'center',
                        key: 'validDate',
                        render: (h, params) => {
                            let validDateStart = new Date(params.row.validDateStart);
                            let validDateEnd = new Date(params.row.validDateEnd);
                            return h('span', validDateStart.getFullYear() + '/' + (validDateStart.getMonth() + 1) + '/' + validDateStart.getDate() + ' ~ ' +
                                validDateEnd.getFullYear() + '/' + (validDateEnd.getMonth() + 1) + '/' + validDateEnd.getDate())
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            let validDateStart = new Date(params.row.validDateStart);
                                            validDateStart = validDateStart.getFullYear() + '-' + (validDateStart.getMonth() + 1) + '-' + validDateStart.getDate()
                                            let validDateEnd = new Date(params.row.validDateEnd);
                                            validDateEnd = validDateEnd.getFullYear() + '-' + (validDateEnd.getMonth() + 1) + '-' + validDateEnd.getDate()
                                            this.validDate1 = validDateStart + '至' + validDateEnd
                                            this.InputData = params.row;
                                            this.model3 = true;
                                            this.getFiles()
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)? '':'#d0d0d0' ,
                                        pointerEvents: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.validDate = [new Date(params.row.validDateStart), new Date(params.row.validDateEnd)]
                                            this.InputData = params.row;
                                            this.model1 = true;
                                            this.add = false;
                                            this.getFiles()
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)? 'red':'#d0d0d0' ,
                                        pointerEvents: (params.row.createUserId == sessionStorage('userId').getObject('userId').userId ||  this.Common.userIdList.includes(sessionStorage('userId').getObject('userId').userId )||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                            ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params.row);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                add: false,
                model1: false,
                model3: false,
                validDate1: '',
                fileUrl: Api.interestedPartiesUserFile,
                validDate: [null, null],
                InputData: {},
                buttonLoading: false,
                uploadList: [],

                pageModel2: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                    contractorName: ''
                },
                contractor: [],
                columns2: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pageModel2.currentPage - 1) * this.pageModel2.pageSize + 1);
                        }
                    },
                    {
                        minWidth: 150,
                        title: '企业名称',
                        align: 'center',
                        key: 'contractorName',
                    },
                    {
                        minWidth: 150,
                        title: '企业性质',
                        align: 'center',
                        key: 'propertyName',
                    },
                    {
                        minWidth: 150,
                        title: '法定代表人',
                        align: 'center',
                        key: 'legalPerson',
                    },
                    {
                        minWidth: 150,
                        title: '注册资本',
                        align: 'center',
                        key: 'capital',
                    },
                    {
                        minWidth: 150,
                        title: '统一社会信用代码',
                        align: 'center',
                        key: 'unifyCode',
                    },
                ],
                model2: false,
                // InputData1: {},
                companyId: '',
            }
        },
        mounted() {
            this.companyId = sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.query()
        },
        methods: {

            // baocun() {
            //     this.InputData.contractorName = this.InputData1.contractorName
            //     this.InputData.contractorId = this.InputData1.contractorId
            //     this.model2 = false
            // },
            danxuan(row, index) {
                this.InputData.contractorId = row.contractorId
                this.InputData.contractorName = row.contractorName
                this.model2 = false
                this.model1 = true
            },
            selectContractor() {
                this.loading = true;
                this.model2 = true
                this.contractor = []
                let data = {
                    startPage: this.pageModel2.currentPage,
                    size: this.pageModel2.pageSize,
                    contractorName: this.pageModel2.contractorName,
                    orgId:sessionStorage('userId').getObject('userId').companyId
                }
                data = Object.assign(data);
                let url = Api.interestedPartiesEvaluateBookList
                this.$http.get(url, {params: data}).then((res) => {
                    console.log(res.data);
                    this.contractor = res.data.data.data;
                    this.pageModel2.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },


            downloadFile(agreementId, file) {
                let url = this.fileUrl + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    console.log(res)
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            remove1(id) {
                console.log(id)
                let url = this.fileUrl + '/file/' + id;
                this.$http.delete(url).then((res) => {
                    this.getFiles()
                })
            },
            beforeUpload(file) {
                console.log(this.uploadList)
                let formData = new FormData();
                formData.append("files", file); // 文件对象
                let url = this.fileUrl + '/' + this.InputData.agreementId + '/files/agreementFile'
                this.$http.post(url, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.info("文件上传成功")
                        this.getFiles();
                    }
                })
                return false
            },
            getFiles() {
                let url = this.fileUrl + '/' + this.InputData.agreementId + '/files/agreementFile'
                this.$http.get(url).then((res) => {
                    if (res.data.result == "success") {
                        console.log(res.data)
                        this.uploadList = res.data.data
                    }
                })
            },

            onCancel() {
                this.validDate = [null, null]
                this.InputData = {}
                this.model1 = false
                this.model3 = false
                this.uploadList = []
                this.query()
            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        this.InputData.validDateStart = this.validDate[0]
                        this.InputData.validDateEnd = this.validDate[1]
                        if (this.add) {
                            let url = Api.interestedPartiesAgreementAdd
                            this.InputData.bsflag = '0'
                            this.InputData.createOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                            this.InputData.createUserId = sessionStorage('userId').getObject('userId').userId
                            this.$http.post(url, this.InputData).then((res) => {
                                this.$Message.success('成功');
                                // this.uploadFile();
                                this.buttonLoading = false
                                this.model1 = false
                                this.query()
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        } else {
                            let url = Api.interestedPartiesAgreementUpdate;
                            this.InputData.updateUserId = sessionStorage('userId').getObject('userId').userId
                            this.InputData.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                            this.$http.post(url, this.InputData).then((res) => {
                                this.$Message.success('成功');
                                // this.uploadFile();
                                this.buttonLoading = false
                                this.model1 = false
                                this.query()
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('失败!');
                    }
                })

            },

            deleteData(row) {
                let url = Api.interestedPartiesAgreementDelete + '/' + row.agreementId
                this.$http.delete(url).then((res) => {
                    this.$Message.success('成功');
                    this.query()
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            addInfo() {
                this.validDate = [null, null]
                this.add = true;
                this.InputData = {
                    agreementId: this.get_uuid()
                };
                this.model1 = true;
            },
            query() {
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize
                }
                if (this.form1.orgId == '') {
                    this.form1.orgId = this.companyId
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                let url = Api.interestedPartiesAgreementList
                this.$http.get(url, {params: data}).then((res) => {
                    console.log(res.data);
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {
                    agreementName: '',
                    contractorName: '',
                    orgId: '',
                    orgName: ''
                }
                this.pageModel2.currentPage = 1;
                this.pageModel2.contractorName = ''
                this.$refs.childOrg.resetCurrentOrg();
                this.query();
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            setOrgId(data) {
                this.form1.orgId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1.orgName = data;
            },
            pageChange1(pageNum) {
                this.pageModel2.currentPage = pageNum;
                this.selectContractor();
            },
            pageSizeChange1(pageSize) {
                this.pageModel2.pageSize = pageSize;
                this.selectContractor();
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },
        }
    }
</script>

<style scoped>
    @import '../../../index.css';
</style>